package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.CommentDetailsAdapter;
import com.runen.infinitemovement.adapter.HeardPictureAdapter;
import com.runen.infinitemovement.adapter.MyDynamicStateChallengeAdapter;
import com.runen.infinitemovement.adapter.MyDynamicStatePictureAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.CommentDetailListBean;
import com.runen.infinitemovement.model.entity.DynamicsDetailsEntuty;
import com.runen.infinitemovement.model.entity.DynamicsEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.ReplyCommentListBean;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.widget.goodview.GoodView;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DynamicStateDetailsActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_iv_right)
    ImageView topIvRight;
    @BindView(R.id.rci_user_header)
    RoundedCornersImage rciUserHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.rv_picture)
    RecyclerView rvPicture;
    @BindView(R.id.rv_challenge)
    RecyclerView rvChallenge;
    @BindView(R.id.rv_liked_picture_list)
    RecyclerView rvLikedPictureList;
    @BindView(R.id.tv_liked_sum)
    TextView tvLikedSum;
    @BindView(R.id.ll_liked)
    LinearLayout llLiked;
    @BindView(R.id.tv_comment_sum)
    TextView tvCommentSum;
    @BindView(R.id.rv_details_comment)
    RecyclerView rvDetailsComment;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.top_btn_right)
    Button top_btn_right;
    @BindView(R.id.iv_praise)
    ImageView ivPraise;
    @BindView(R.id.rl_like)
    RelativeLayout rlLike;
    @BindView(R.id.tv_praise_sum)
    TextView tvPraiseSum;
    @BindView(R.id.edt_input_message)
    EditText edtInputMessage;
    @BindView(R.id.iv_map_img)
    ImageView ivMapImg;
    private MyDynamicStatePictureAdapter dynamicStatePictureAdapter;
    private MyDynamicStateChallengeAdapter challengeAdapter;
    private CommentDetailsAdapter commentDetailsAdapter;
    private String userId;
    private String dynamicId;
    private HeardPictureAdapter heardPictureAdapter;
    private CommentDetailListBean commentDetailListBean;
    private ReplyCommentListBean replyCommentListBean;
    private String topItemCommentId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_dynamic_state_details;
    }


    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        top_btn_right.setVisibility(View.GONE);
        userId = getIntent().getStringExtra("userId");
        dynamicId = getIntent().getStringExtra("dynamicId");
        srl.setOnRefreshListener(this);
        if (UserAPI.getUserId().equals(userId)) {
            GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_delete), topIvRight);
            topIvRight.setVisibility(View.VISIBLE);
        } else {
            topIvRight.setVisibility(View.GONE);
        }
        topTitle.setText("动态详情");
        LinearLayoutManager layoutManager4 = new LinearLayoutManager(this);
        layoutManager4.setOrientation(RecyclerView.HORIZONTAL);
        rvLikedPictureList.setLayoutManager(layoutManager4);
        heardPictureAdapter = new HeardPictureAdapter(this);
        rvLikedPictureList.setAdapter(heardPictureAdapter);

        /**
         * 图片
         */
        LinearLayoutManager layoutManager = new GridLayoutManager(this, 3);
        rvPicture.setLayoutManager(layoutManager);
        dynamicStatePictureAdapter = new MyDynamicStatePictureAdapter(this);
        rvPicture.setAdapter(dynamicStatePictureAdapter);
        dynamicStatePictureAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArrayList<String> list = new ArrayList<>();
                for (int j = 0; j < dynamicStatePictureAdapter.getData().size(); j++) {
                    list.add(dynamicStatePictureAdapter.getData().get(j));
                }
                Intent intent = new Intent(DynamicStateDetailsActivity.this, PhotoActivity.class);
                intent.putExtra("position", position);
                intent.putStringArrayListExtra("list", list);
                startActivity(intent);
            }
        });
        /**
         * 挑战
         */
//        StaggeredGridLayoutManager challengeLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        LinearLayoutManager challengeLayoutManager = new LinearLayoutManager(this);
        challengeLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvChallenge.setLayoutManager(challengeLayoutManager);
        challengeAdapter = new MyDynamicStateChallengeAdapter(this);
        rvChallenge.setAdapter(challengeAdapter);

        /**
         * 评论
         */
        LinearLayoutManager commentLayoutManager = new LinearLayoutManager(this);
        commentLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvDetailsComment.setLayoutManager(commentLayoutManager);
        commentDetailsAdapter = new CommentDetailsAdapter(this);
        rvDetailsComment.setAdapter(commentDetailsAdapter);


        initData();

        commentDetailsAdapter.setOnItemCommentClick(new CommentDetailsAdapter.OnItemCommentClick() {
            @Override
            public void onItemPraise(CommentDetailListBean item) {
                sendOrCancelPrise(item);
            }

            @Override
            public void onItemCommentReply(CommentDetailListBean item, String topCommentId) {
                //评论回复
                commentDetailListBean = item;
                topItemCommentId = topCommentId;
                edtInputMessage.setHint("回复" + item.nickname + "：");
                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemSecondReply(ReplyCommentListBean item, String topCommentId) {
                replyCommentListBean = item;
                topItemCommentId = topCommentId;
                edtInputMessage.setHint("回复" + item.reviewerName + "：");
                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemMore(CommentDetailListBean item, String topCommentId) {
                Intent intent = new Intent(DynamicStateDetailsActivity.this, SecondReplyCommentActivity.class);
                intent.putExtra("commentId", item.commentId);
                intent.putExtra("targetId", dynamicsData.id);
                startActivity(intent);
            }
        });
        edtInputMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {//修改回车键功能
                    //代码
                    String edtString = v.getText().toString().trim();
                    if (TextUtils.isEmpty(edtString)) {
                        ToastUtils.showShort("请输入评论信息！！！");
                    } else {
                        onComment(edtString, commentDetailListBean, replyCommentListBean);
                    }
                }
                return false;
            }
        });
    }

    /**
     * 评论点赞
     *
     * @param CommentDetailListBean
     * @param
     */
    private void sendOrCancelPrise(CommentDetailListBean CommentDetailListBean) {
        JSONObject object = new JSONObject();
        try {
            object.put("toLikeUserId", CommentDetailListBean.reviewerId);
            object.put("likeDataId", CommentDetailListBean.commentId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().commentLikeAndCancel(CommentDetailListBean.isLike, object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();

            }
        });
    }

    private void initData() {
        srl.setRefreshing(true);
        String string = "?dynamicId=%s";
        new ActivityAPI().onDynamicStateDetails(String.format(string, dynamicId), new BaseResultCallback<DynamicsDetailsEntuty>() {
            @Override
            public void onResponse(DynamicsDetailsEntuty response) {
                srl.setRefreshing(false);
                if (response.code == 0) {
                    if (response.data != null) {
                        setView(response.data);
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                srl.setRefreshing(false);
            }

            @Override
            public void onComplete() {
                super.onComplete();
                srl.setRefreshing(false);
            }
        });
    }

    private DynamicsEntity dynamicsData;

    private void setView(DynamicsEntity dynamicsEntity) {
        dynamicsData = dynamicsEntity;
        GlideUtils.loadImage(this, dynamicsEntity.headImgUrl, rciUserHeader);
        tvName.setText(dynamicsEntity.nickname);
        tvDescribe.setText(dynamicsEntity.content);
        tvDate.setText(TimeUtil.dealDateFormat(dynamicsEntity.createTime));
        String likeNum = "%s 人赞过";
        tvLikedSum.setText(String.format(likeNum, dynamicsEntity.likeNumber));
        String commentNum = "（%s）";
        tvCommentSum.setText(String.format(commentNum, dynamicsEntity.commentNumber));
        dynamicStatePictureAdapter.setNewData(dynamicsEntity.images);
        if (TextUtils.isEmpty(dynamicsEntity.motionImage)) {
            ivMapImg.setVisibility(View.GONE);
        } else {
            GlideUtils.loadImage(this, dynamicsEntity.motionImage, ivMapImg);
        }

        if (dynamicsEntity.activityNames != null && dynamicsEntity.activityNames.size() > 0) {
            challengeAdapter.setNewData(dynamicsEntity.activityNames);
            rvChallenge.setVisibility(View.VISIBLE);
        } else {
            rvChallenge.setVisibility(View.GONE);
        }
        tvPraiseSum.setText(String.valueOf(dynamicsEntity.likeNumber));
        heardPictureAdapter.setNewData(dynamicsEntity.likeHeadImages);
        commentDetailsAdapter.setNewData(dynamicsEntity.commentsPageDto);
        if (dynamicsEntity.isLike) {
            GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_praised), ivPraise);
        } else {
            GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_like), ivPraise);
        }
    }

    @OnClick({R.id.top_btn_left, R.id.top_iv_right, R.id.ll_liked, R.id.rl_like, R.id.rci_user_header})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.top_iv_right:
                delete();
                break;
            case R.id.ll_liked:
                Intent intent = new Intent(this, ReceiveLikedActivity.class);
                intent.putExtra("dynamicId", dynamicId);
                startActivity(intent);
                break;
            case R.id.rl_like:
                if (null != dynamicsData) {
                    if (dynamicsData.isLike) {
                        dynamicsData.likeNumber = dynamicsData.likeNumber - 1;
                        dynamicsData.isLike = false;
                        GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_like), ivPraise);
                    } else {
                        dynamicsData.likeNumber = dynamicsData.likeNumber + 1;
                        dynamicsData.isLike = true;
                        GoodView goodView = new GoodView(this);
                        goodView.setImage(R.mipmap.ico_praised);
                        goodView.show(ivPraise);
                        GlideUtils.loadImage(this, CommonUtil.getDrawable(R.mipmap.ico_praised), ivPraise);
                    }
                    String likeNum = "%s 人赞过";
                    tvLikedSum.setText(String.format(likeNum, dynamicsData.likeNumber));
                    tvPraiseSum.setText(String.valueOf(dynamicsData.likeNumber));
                    onPraise(dynamicsData);
                }
                break;
            case R.id.rci_user_header:
                if (null != dynamicsData) {
                    Intent intent2 = new Intent(this, MyHomeActivityV2.class);
                    intent2.putExtra("userId", dynamicsData.userId);
                    startActivity(intent2);
                }
                break;
        }
    }

    private void delete() {
        CommonDialog.getInstance(this, "", "确定删除？", "取消", "删除", 0).setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void onSendListener() {
            }

            @Override
            public void onDismiss() {
                onDelete();
            }
        });
    }

    /**
     * 删除动态
     */
    private void onDelete() {
        JSONObject object = new JSONObject();
        try {
            object.put("dynamicId", dynamicId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        showDialog();
        new ActivityAPI().onDelete(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                dismissDialog();
            }

            @Override
            public void onComplete() {
                super.onComplete();
                ToastUtils.showShort("删除成功");
                EventBus.getDefault().post(new EventBusEntity(8));
                dismissDialog();
                finish();
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });

    }

    @Override
    public void onRefresh() {
        initData();
    }

    private void onPraise(DynamicsEntity item) {
        JSONObject object = new JSONObject();
        try {
            object.put("likeDataId", item.id);
            object.put("toLikeUserId", item.userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onPraise(object.toString(), item.isLike, new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                if (item.isLike) {
                    ToastUtils.showShort("点赞成功");
                } else {
                    ToastUtils.showShort("取消点赞成功");
                }
            }
        });
    }


    /**
     * 对文章的评论
     *
     * @param edtString
     */
    private void onComment(String edtString, final CommentDetailListBean commentDetailList, final ReplyCommentListBean replyCommentList) {
        JSONObject object = new JSONObject();
        try {
            object.put("commentType", "1");
            object.put("content", edtString);
            object.put("targetId", dynamicsData.id);
            object.put("replyUserId", dynamicsData.userId);
            if (null != commentDetailList) {
                object.put("replyId", commentDetailList.commentId);
                object.put("replyUserId", commentDetailList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            } else if (null != replyCommentList) {
                object.put("replyArticleCommentsId", replyCommentList.commentId);
                object.put("replyUserId", replyCommentList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onDynamicComment(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                CommonUtil.hideKeyboard(DynamicStateDetailsActivity.this);
                edtInputMessage.setText("");
                edtInputMessage.setHint("说点什么...");
                commentDetailListBean = null;
                replyCommentListBean = null;
                onRefresh();
            }
        });
    }


}
